package com.glorysoft.wangnianxinpda.activity;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.glorysoft.wangnianxinpda.R;
import com.glorysoft.wangnianxinpda.adapter.AbnoamlCodeDialogAdapter;
import com.glorysoft.wangnianxinpda.adapter.AbnomalCodeAdapter;
import com.glorysoft.wangnianxinpda.base.App;
import com.glorysoft.wangnianxinpda.base.BaseActivity;
import com.glorysoft.wangnianxinpda.base.Constant;
import com.glorysoft.wangnianxinpda.databinding.ActivityBatchWorkEndBinding;
import com.glorysoft.wangnianxinpda.entity.AbnomalCodeEntity;
import com.glorysoft.wangnianxinpda.entity.PDAToQueryReturnEntity;
import com.glorysoft.wangnianxinpda.entity.PDATrackOutEntity;
import com.glorysoft.wangnianxinpda.entity.net.ResponseEntity;
import com.glorysoft.wangnianxinpda.utils.MyUtils;
import com.glorysoft.wangnianxinpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;


public class BatchWorkEndActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;

    private String sEqpID;//设备号

    private PDAToQueryReturnEntity mPDAToQueryReturnEntity;//结束信息
    private List<AbnomalCodeEntity> mabnomalCodeList;//不良代码列表(集合不变)
    private List<AbnomalCodeEntity> mabnomalCodeSecondList;//实际出现的不良代码
    private List<PDATrackOutEntity> pdaTrackOutList;//树脂、料盒集合
    private AbnomalCodeAdapter mAdapter;//不良代码适配器

    private int totalCodeNum = 0;//总不良数
    private String sCurBadNo = "";//当前选择的不良代码

    private String sTotalQty = "";//总投入数
    private int nTotalQty = 0;//总投入数

    private String sOKQty = "";//OK数
    private int nOKQty = 0;//OK数

    private String sLastClassReportQty = "";//上一班次汇报产量
    private int nLastClassReportQty = 0;//上一班次汇报产量

    private FreeUI_GeneralFragmentDialog mAbnoamlCodeDialog;//不良代码选择框

    private FreeUI_GeneralFragmentDialog mMessageDialog;//消息提示框

    private ActivityBatchWorkEndBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    @Override
    protected void initView() {
        mContext = this;

        binding = DataBindingUtil.setContentView(this, R.layout.activity_batch_work_end);
        binding.rvFailOutList.setLayoutManager(new LinearLayoutManager(mContext));
        binding.rvFailOutList.setItemAnimator(new DefaultItemAnimator());
        binding.rvFailOutList.addItemDecoration(new DividerItemDecoration(mContext, 1));

        binding.flBadReason.setOnClickListener(this);//选择不良原因
        binding.tvAddBadCode.setOnClickListener(this);//添加
        binding.tvRemoveBadCode.setOnClickListener(this);//移除
        binding.cbCheckAllBadCode.setOnClickListener(this);//全选

        initCarrierEdit();

    }

    private void initCarrierEdit() {
        binding.etCarrierId2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().isEmpty())return;
                if (binding.etCarrierId1.getText().toString().trim().isEmpty()){
                    showToast("请按顺序输入料盒号",false);
                    binding.etCarrierId2.setText("");
                }
            }
        });

        binding.etCarrierId3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().isEmpty())return;
                if (binding.etCarrierId1.getText().toString().trim().isEmpty() || binding.etCarrierId2.getText().toString().trim().isEmpty()){
                    showToast("请按顺序输入料盒号",false);
                    binding.etCarrierId3.setText("");
                }
            }
        });

        binding.etCarrierId4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().isEmpty())return;
                if (binding.etCarrierId1.getText().toString().trim().isEmpty() || binding.etCarrierId2.getText().toString().trim().isEmpty()
                        || binding.etCarrierId3.getText().toString().trim().isEmpty()){
                    showToast("请按顺序输入料盒号",false);
                    binding.etCarrierId4.setText("");
                }
            }
        });

        binding.etCarrierId5.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().isEmpty())return;
                if (binding.etCarrierId1.getText().toString().trim().isEmpty() || binding.etCarrierId2.getText().toString().trim().isEmpty()
                        || binding.etCarrierId3.getText().toString().trim().isEmpty() || binding.etCarrierId4.getText().toString().trim().isEmpty()){
                    showToast("请按顺序输入料盒号",false);
                    binding.etCarrierId5.setText("");
                }
            }
        });

        binding.etCarrierId6.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().isEmpty())return;
                if (binding.etCarrierId1.getText().toString().trim().isEmpty() || binding.etCarrierId2.getText().toString().trim().isEmpty()
                        || binding.etCarrierId3.getText().toString().trim().isEmpty() || binding.etCarrierId4.getText().toString().trim().isEmpty()
                        || binding.etCarrierId5.getText().toString().trim().isEmpty()){
                    showToast("请按顺序输入料盒号",false);
                    binding.etCarrierId6.setText("");
                }
            }
        });
    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        sEqpID = extras.getString("EQPID");
        mabnomalCodeSecondList = new ArrayList<>();
//        tv_eqp_id.setText(sEqpID);
        mAdapter = new AbnomalCodeAdapter(R.layout.adapter_abnomal_code, mabnomalCodeSecondList);
        binding.rvFailOutList.setLayoutManager(new LinearLayoutManager(mContext));
        binding.rvFailOutList.setAdapter(mAdapter);
        binding.tvEqpNo.setText(sEqpID);

//        MyUtils.setNewEditTextListener(binding.etTotalNum, mContext, s -> {
//            sTotalQty = s;
//            nTotalQty = Integer.parseInt(sTotalQty.equals("") ? "0" : sTotalQty);
//            caculateGoodRate();//计算总不良数
//        });

       /* mPDAToQueryReturnEntity = new PDAToQueryReturnEntity();
        mPDAToQueryReturnEntity.setINPUTQTY("10000");
        mPDAToQueryReturnEntity.setCHANGESHIFTS_COUNT("0");
        List<AbnomalCodeEntity> abnomalCodeEntities = new ArrayList<>();
        for (int i = 1; i < 3; i++) {
            AbnomalCodeEntity abnomalCodeEntity = new AbnomalCodeEntity();
            abnomalCodeEntity.setABNOMAL_ID(i + "");
            abnomalCodeEntity.setABNOMAL_REASON(i + "");
            abnomalCodeEntity.setABNOMAL_QTY(String.valueOf(10 * i));
            abnomalCodeEntities.add(abnomalCodeEntity);
        }
        mPDAToQueryReturnEntity.setABNOMAL_CODES(abnomalCodeEntities);
        mabnomalCodeList = mPDAToQueryReturnEntity.getABNOMAL_CODES();//该集合用于显示所有不良品代码，获取后不可再做更改。
        binding.setEntity(mPDAToQueryReturnEntity);
        sTotalQty = mPDAToQueryReturnEntity.getINPUTQTY();//来料数量
        nTotalQty = sTotalQty.equals("") ? 0 : Integer.parseInt(sTotalQty);//来料数量
        sLastClassReportQty = mPDAToQueryReturnEntity.getCHANGESHIFTS_COUNT();
        nLastClassReportQty = sLastClassReportQty.equals("") ? 0 : Integer.parseInt(sLastClassReportQty);
        nOKQty = nTotalQty - nLastClassReportQty;
        nOKQty = Math.max(nOKQty, 0);
        sOKQty = String.valueOf(nOKQty);
        binding.tvActualOutput.setText(sOKQty);
        caculateGoodRate();*/
//        toQuery();//获取设备信息

        FreeApi_EditTextUtils.setEditTextListener(binding.etLot, this, new FreeUI_TextCallback() {
            @Override
            public void onSuccess(String s) {
                toQuery(s);//获取设备信息
            }
        });

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.batchEndOperation));
        freeUI_titleView.setRightListener(getString(R.string.finishWork), v -> {
            if(mPDAToQueryReturnEntity == null){
                showToast("请先扫描批次号", false);
                return;
            }
            if (compareTotalQty(v) > 0){
//                showToast(String.format(getString(R.string.good_nums_add_abnormal_nums_can_not_bigger_total_nums), TextUtils.isEmpty(mPDAToQueryReturnEntity.getINPUTQTY()) ? "0" : mPDAToQueryReturnEntity.getINPUTQTY()), false);
                showToast(String.format(getString(R.string.good_nums_add_abnormal_nums_can_not_bigger_total_nums), sTotalQty), false);
            }else if (compareTotalQty(v) < 0){
//                showToast(String.format(getString(R.string.good_nums_add_abnormal_nums_can_not_lower_total_nums), TextUtils.isEmpty(mPDAToQueryReturnEntity.getINPUTQTY()) ? "0" : mPDAToQueryReturnEntity.getINPUTQTY()), false);
                showToast(String.format(getString(R.string.good_nums_add_abnormal_nums_can_not_lower_total_nums), sTotalQty), false);
            }else {

                getParams();
                trackOut();//结束作业

                //region 测试
//                showMessageDialog("结束作业成功", getSupportFragmentManager());
                //endregion
            }

        });
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), binding.llMain);
    }

    //计算合格率
    private void caculateGoodRate(){
        double goodRate = 0;
        if (nTotalQty == 0){
            goodRate = 0;
        }else {
            goodRate = new BigDecimal(sOKQty).divide(new BigDecimal(sTotalQty), 4, RoundingMode.HALF_UP).doubleValue();
//            goodRate = Double.parseDouble(sOKQty)/Double.parseDouble(sTotalQty);
//            BigDecimal b = new BigDecimal(goodRate);
//            goodRate = b.setScale(4, RoundingMode.HALF_UP).doubleValue();
        }
        binding.tvPassRate.setText(goodRate * 100 + "%");
    }
    //获取树脂、料盒数据
    private void getParams() {
        pdaTrackOutList = new ArrayList<>();
//        pdaTrackOutList.add(new PDATrackOutEntity("料盒号1", binding.etCarrierId1.getText().toString().trim()));
//        pdaTrackOutList.add(new PDATrackOutEntity("料盒号2", binding.etCarrierId2.getText().toString().trim()));
//        pdaTrackOutList.add(new PDATrackOutEntity("料盒号3", binding.etCarrierId3.getText().toString().trim()));
//        pdaTrackOutList.add(new PDATrackOutEntity("料盒号4", binding.etCarrierId4.getText().toString().trim()));
//        pdaTrackOutList.add(new PDATrackOutEntity("料盒号5", binding.etCarrierId5.getText().toString().trim()));
//        pdaTrackOutList.add(new PDATrackOutEntity("料盒号6", binding.etCarrierId6.getText().toString().trim()));
//        pdaTrackOutList.add(new PDATrackOutEntity("树脂标签", binding.etResinId.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("XBOX1", binding.etCarrierId1.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("XBOX2", binding.etCarrierId2.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("XBOX3", binding.etCarrierId3.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("XBOX4", binding.etCarrierId4.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("XBOX5", binding.etCarrierId5.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("XBOX6", binding.etCarrierId6.getText().toString().trim()));
        pdaTrackOutList.add(new PDATrackOutEntity("LabelEntry", binding.etResinId.getText().toString().trim()));
    }

    //region 不良代码

    private void showAbnomalCode(){
        if (mabnomalCodeList != null){
            if (mabnomalCodeList.size() > 0){
                showAbnomalCodeDialog(mabnomalCodeList);
            }else {
                showToast(getString(R.string.do_no_have_abnaml_code), true);
            }
        }
    }

    //不良代码选择框
    private void showAbnomalCodeDialog(List<AbnomalCodeEntity> list){
        mAbnoamlCodeDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_reject_code, null);
        Button btn_cancel = view.findViewById(R.id.btn_cancel);
        RecyclerView rv_reject_code = view.findViewById(R.id.rv_reject_code);
        btn_cancel.setOnClickListener(v -> mAbnoamlCodeDialog.dismiss());
        mAbnoamlCodeDialog.setLayout(view);
        mAbnoamlCodeDialog.show(getSupportFragmentManager(), "abnomalCodeSelect");
        mAbnoamlCodeDialog.setCallBack(() -> mAbnoamlCodeDialog = null);//弹出框退出后赋空
        AbnoamlCodeDialogAdapter mAdapter = new AbnoamlCodeDialogAdapter(R.layout.adapter_abnomal_code_dialog, list);
        rv_reject_code.setLayoutManager(new LinearLayoutManager(mContext));
        rv_reject_code.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener((adapter, view1, position) -> {
            binding.tvBadReason.setText(list.get(position).getABNOMAL_REASON());
            sCurBadNo = list.get(position).getABNOMAL_ID();
            mAbnoamlCodeDialog.dismiss();
        });
    }

    //添加不良品
    private void addAbnomalCode(){
        String sAbnomalReason = binding.tvBadReason.getText().toString();
        String sNum = binding.etNum.getText().toString();
        int num = Integer.parseInt(sNum.equals("") ? "0" : sNum);
        boolean isAdded = false;//判断该不良代码是否已经添加过
        mabnomalCodeSecondList = mAdapter.getData();//更新列表数据

        ArrayList<AbnomalCodeEntity> abnomalCodeEntities = new ArrayList<>();//存储被选中的数据
        //判断是否选择了不良代码
        if (!TextUtils.isEmpty(sCurBadNo)){

            //判断是否输入了不良数量
            if (!TextUtils.isEmpty(sNum)){

                //判断是否有已添加的不良代码
                if (!mabnomalCodeSecondList.isEmpty()){

                    for (AbnomalCodeEntity entity:
                         mabnomalCodeSecondList) {

                        //判断该不良代码是否已经添加过
                        if (entity.getABNOMAL_ID().equals(sCurBadNo)){
                            int qty = Integer.parseInt(entity.getABNOMAL_QTY());

                            //更新不良数量
                            qty += num;
                            entity.setABNOMAL_QTY(String.valueOf(qty));

                            isAdded = true;
                        }

                        //获取被勾选的数据
                        if (entity.isChecked()){
                            abnomalCodeEntities.add(entity);
                        }
                        
                    }
                    //如果该不良代码没有添加过，则添加
                    if (!isAdded){
                        AbnomalCodeEntity abnomalCodeEntity = new AbnomalCodeEntity();
                        abnomalCodeEntity.setABNOMAL_ID(sCurBadNo);
                        abnomalCodeEntity.setABNOMAL_QTY(String.valueOf(num));
                        abnomalCodeEntity.setABNOMAL_REASON(sAbnomalReason);
                        mabnomalCodeSecondList.add(abnomalCodeEntity);

                        abnomalCodeEntities.add(abnomalCodeEntity);//存储被勾选的数据
                    }

                }else {
                    AbnomalCodeEntity abnomalCodeEntity = new AbnomalCodeEntity();
                    abnomalCodeEntity.setABNOMAL_ID(sCurBadNo);
                    abnomalCodeEntity.setABNOMAL_QTY(String.valueOf(num));
                    abnomalCodeEntity.setABNOMAL_REASON(sAbnomalReason);

                    mabnomalCodeSecondList.add(abnomalCodeEntity);

                    abnomalCodeEntities.add(abnomalCodeEntity);//存储被勾选的数据

                }

                //更新总不良品数
                mAdapter.setNewData(mabnomalCodeSecondList);
                mAdapter.setList(abnomalCodeEntities);//存储被勾选的数据
                totalCodeNum += num;
                nOKQty = nTotalQty - totalCodeNum - nLastClassReportQty;//自动计算合格数
                sOKQty = String.valueOf(nOKQty);
                binding.tvActualOutput.setText(sOKQty);
                binding.tvAbnomalNum.setText(String.valueOf(totalCodeNum));
                caculateGoodRate();//计算合格率
                showToast(getString(R.string.addSuccess), true);

            }else {
                showToast(getString(R.string.please_input_abnomal_num), false);
            }
        }else {
            showToast(getString(R.string.please_chose_abnomal_reason), false);
        }
    }

    //删除不良品
    private void deleteAbnomalCode(){

        //获取待删除数据
        ArrayList<AbnomalCodeEntity> deleteData = new ArrayList<>(mAdapter.getList());

        if (!deleteData.isEmpty()){

            //删除已选择的不良代码
            mabnomalCodeSecondList.removeAll(deleteData);
            mAdapter.setNewData(mabnomalCodeSecondList);

            mAdapter.setList(new ArrayList<AbnomalCodeEntity>());//清空已删除的不良代码

            //更新总不良数
            for (AbnomalCodeEntity entity:
                 deleteData) {
                String qty = entity.getABNOMAL_QTY();
                totalCodeNum -= Integer.parseInt(qty);
            }
            binding.tvAbnomalNum.setText( totalCodeNum < 0 ? "0" : String.valueOf(totalCodeNum));
//            binding.tvAbnomalNum.setText( String.valueOf(totalCodeNum));

            nOKQty = nTotalQty - totalCodeNum - nLastClassReportQty;//自动计算合格数
            sOKQty = String.valueOf(nOKQty);
            binding.tvActualOutput.setText(sOKQty);
            caculateGoodRate();//计算合格率
            showToast(getString(R.string.deleteSuccess), true);

        }else {
            showToast(getString(R.string.please_chose_delete_data), false);

        }
        binding.cbCheckAllBadCode.setChecked(false);
    }

    //判断总数是否等于合格数与不良数
    private int compareTotalQty(View view){
        int abnomalTotalQty = Integer.parseInt(binding.tvAbnomalNum.getText().toString());//总不良数
        int badNum = 0;

        if (!binding.etNum.getText().toString().equals("")){
            badNum = Integer.parseInt(binding.etNum.getText().toString());//待添加不良数
        }

        int goodNum = 0;
        if (!binding.tvActualOutput.getText().toString().equals("")){
            goodNum = Integer.parseInt(binding.tvActualOutput.getText().toString());
        }else {
            mPDAToQueryReturnEntity.setOUTPUTQTY("0");
            goodNum = 0;
            binding.setEntity(mPDAToQueryReturnEntity);
        }

        //判断点击事件是添加还是结束作业
        if (view.getId() == R.id.tvAddBadCode){
//            return (abnomalTotalQty + badNum + goodNum) - Integer.parseInt(TextUtils.isEmpty(mPDAToQueryReturnEntity.getINPUTQTY()) ? "0" : mPDAToQueryReturnEntity.getINPUTQTY());
            return (abnomalTotalQty + badNum + nLastClassReportQty) - nTotalQty;
        }else {
//            return (abnomalTotalQty + goodNum) - Integer.parseInt(TextUtils.isEmpty(mPDAToQueryReturnEntity.getINPUTQTY()) ? "0" : mPDAToQueryReturnEntity.getINPUTQTY());
            return (abnomalTotalQty + goodNum + nLastClassReportQty) - nTotalQty;
        }
    }

    //endregion

    //region 接口调用

    //结束作业
    private void trackOut() {
        FreeUI_EntityCallBack<ResponseEntity<?>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<?>>(new TypeToken<ResponseEntity<?>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<?>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(false, getSupportFragmentManager())) {
//                    finish();
                    showMessageDialog(response.body().getMsg(), getSupportFragmentManager());

                }
            }

            @Override
            public void onError(Response<ResponseEntity<?>> response) {
                super.onError(response);
                loadError(response.getException(), "PDATrackOut");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());//工号
        map.addProperty("EQPID", mPDAToQueryReturnEntity.getEQPID());//设备号
        map.addProperty("LOTID", mPDAToQueryReturnEntity.getLOTID());//工单号
//        map.addProperty("INPUTQTY", mPDAToQueryReturnEntity.getINPUTQTY());//来料数量（良品数）
        map.addProperty("INPUTQTY", sTotalQty);//来料数量（良品数）
        map.addProperty("CURRENTPROCESS", mPDAToQueryReturnEntity.getCURRENTPROCESS());//当前工序（当前工单系统中所在站点）
        map.addProperty("TRACKINTIME", mPDAToQueryReturnEntity.getTRACKINTIME());//开始时间
        map.addProperty("TRACKOUTTIME", mPDAToQueryReturnEntity.getTRACKOUTTIME());//结束时间
        map.addProperty("OUTPUTQTY", sOKQty);//产出数量（为0时则需要用户手动输入）
        map.addProperty("ABNOMAL_CODES", new Gson().toJson(mabnomalCodeSecondList));//报废代码集合
        map.addProperty("PARAMETERLS",new Gson().toJson(pdaTrackOutList));//料盒号、树脂标签编号（选填）
//        map.addProperty("RESINTAGID", binding.etResinId.getText().toString().trim());//树脂标签编号（选填）
        map.addProperty("ItemBox", binding.etItemBox.getText().toString().trim());
        String method = "PDATrackOut";
        NetUtils.requestPostNet("PDATrackInRequest", method, this, map, callBack);
    }

    //获取设备信息
    private void toQuery(String s){
        FreeUI_EntityCallBack<ResponseEntity<PDAToQueryReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<PDAToQueryReturnEntity>>(new TypeToken<ResponseEntity<PDAToQueryReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<PDAToQueryReturnEntity>> response) {
                super.onSuccess(response);
                showToast(getString(R.string.success), true);
                if (response.body().isSuccess(true, getSupportFragmentManager())) {
                    mPDAToQueryReturnEntity = response.body().getData();
                    mabnomalCodeList = mPDAToQueryReturnEntity.getABNOMAL_CODES();//该集合用于显示所有不良品代码，获取后不可再做更改。
                    binding.setEntity(mPDAToQueryReturnEntity);
                    sTotalQty = mPDAToQueryReturnEntity.getINPUTQTY();//来料数量
                    nTotalQty = sTotalQty.equals("") ? 0 : Integer.parseInt(sTotalQty);//来料数量
                    sLastClassReportQty = mPDAToQueryReturnEntity.getCHANGESHIFTS_COUNT();
                    nLastClassReportQty = sLastClassReportQty.equals("") ? 0 : Integer.parseInt(sLastClassReportQty);
                    nOKQty = nTotalQty - nLastClassReportQty;
                    nOKQty = Math.max(nOKQty, 0);
                    sOKQty = String.valueOf(nOKQty);
                    binding.tvActualOutput.setText(sOKQty);
                    binding.tvEqpNo.setText(mPDAToQueryReturnEntity.getEQPID());
                    caculateGoodRate();
                }
            }

            @Override
            public void onError(Response<ResponseEntity<PDAToQueryReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDATOQuery");
                showMessageDialog("请退出并重新扫描设备号", getSupportFragmentManager());
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());//工号
        map.addProperty("EQPID", sEqpID);//设备号
        map.addProperty("LOTID", s);//设备号
        String method = "PDATOQuery";
        NetUtils.requestPostNet("PDATOQueryRequest", method, this, map, callBack);
    }



    //endregion

    //消息提示框
    private void showMessageDialog(String message, FragmentManager fragmentManager) {
        FreeApi_DialogUtils.getConfirmDialog(
                App.app, "确定", message, this::finish
        ).show(fragmentManager, "DIALOG");

    }
    //消息提示框
    private void showMessageDialog(String message) {
        mMessageDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_prompt, null);
        Button btnConfirm = view.findViewById(R.id.btnConfirm);
        TextView tvTips = view.findViewById(R.id.tvTips);
        btnConfirm.setOnClickListener(v -> {
            mMessageDialog.dismiss();
            finish();
        });
        tvTips.setText(message);
        mMessageDialog.setLayout(view);
//        mDieTypeDialog.getDialog().setCanceledOnTouchOutside(false);
        mMessageDialog.show(getSupportFragmentManager(), "EndProcess");
        mMessageDialog.setCallBack(() -> mMessageDialog = null);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(mPDAToQueryReturnEntity == null){
            showToast("请先扫描批次号", false);
            return;
        }
        if (id == R.id.flBadReason){
            showAbnomalCode();//选择不良代码
        }else if (id == R.id.tvAddBadCode){
            if (compareTotalQty(v) > 0){
//                showToast(String.format(getString(R.string.good_nums_add_abnormal_nums_can_not_bigger_total_nums), TextUtils.isEmpty(mPDAToQueryReturnEntity.getINPUTQTY()) ? "0" : mPDAToQueryReturnEntity.getINPUTQTY()),false);
                showToast(String.format(getString(R.string.good_nums_add_abnormal_nums_can_not_bigger_total_nums), sTotalQty),false);
            }else {
                addAbnomalCode();//添加
            }
        }else if (id == R.id.tvRemoveBadCode){
            deleteAbnomalCode();//删除
        }else if (id == R.id.cbCheckAllBadCode){
            mAdapter.setAllChecked(binding.cbCheckAllBadCode.isChecked());
        }
    }
}